//
//  BaseVM.m
//  Customer
//
//  Created by tangang on 2017/8/23.
//  Copyright © 2017年 tangang. All rights reserved.
//



#import "BaseVM.h"
#import <CoreLocation/CoreLocation.h>
#import "AFNetworkReachabilityManager.h"
#import "WMKeyChain.h"
#import "LoginVC.h"
@interface BaseVM()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) void (^locationBlock)(void);

@end

@implementation BaseVM{
    CLLocationCoordinate2D  coor;
}

- (NSURLSessionDataTask *)POST_Field_Url:(NSString *)url
                                  Params:( id )params
                            successBlock:(SuccessBlock)success
                               failBlock:(FailBlock)fail
{
    //拼接路径
    NSString *urlStr =  [NSString stringWithFormat:@"%@%@" , C_Header , url];
    WS(weakSelf);
    NSURLSessionDataTask * operation = [[self httpManager] POST:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary *dic=responseObject;
        success(dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        NSString *errorMessage ;
        NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
        NSDictionary *respondObject = [self dictionaryWithJsonString:errResponse];
        if ([[respondObject objectForKey:@"Code"] intValue]==APIResponseStutusUnauthorized) {
            [weakSelf login];
        }else{
            if ([respondObject objectForKey:@"Desc"]) {
                errorMessage =[respondObject objectForKey:@"Desc"];
            }else
            {
                errorMessage = error.localizedDescription;
            }
            if (fail) {
                fail( errorMessage , error);
            }
        }
        
    }];
    return operation;
}


- (NSURLSessionDataTask *)GET_Field_Url:(NSString *)url
                                 Params:( id )params
                           successBlock:(SuccessBlock)success
                              failBlock:(FailBlock)fail
{
    //拼接路径
    NSString * urlStr=[NSString stringWithFormat:@"%@%@" , C_Header , url];
    WS(weakSelf);
    NSURLSessionDataTask * operation  = [[self httpManager] GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary *dic=responseObject;
        if (dic) {
            if (success) {
                success(dic);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        NSString *errorMessage ;
        NSLog(@"%@",url);
        NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errResponse);
        NSDictionary *respondObject = [self dictionaryWithJsonString:errResponse];
        if ([[respondObject objectForKey:@"Code"] intValue]==APIResponseStutusUnauthorized) {
            [weakSelf login];
        }else{
            if ([respondObject objectForKey:@"Desc"]) {
                errorMessage =[respondObject objectForKey:@"Desc"];
            }else
            {
                errorMessage = error.localizedDescription;
            }
            if (fail) {
                fail( errorMessage , error);
            }
        }
    }];
    
    return operation;
}

- (NSURLSessionDataTask *)getBanInfoWithCardId:(NSString *)card successBlock:(SuccessBlock)success failBlock:(FailBlock)fail{
    //拼接路径
    NSString * urlStr=[NSString stringWithFormat:@"https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=%@&cardBinCheck=true",card];
    
    NSURLSessionDataTask * operation  = [[self httpManager] GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary *dic=responseObject;
        if (dic) {
            if (success) {
                success(dic);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        NSString *errorMessage ;
        NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errResponse);
        NSDictionary *respondObject = [self dictionaryWithJsonString:errResponse];
        if ([[respondObject objectForKey:@"error"] objectForKey:@"message"]) {
            errorMessage =[[respondObject objectForKey:@"error"] objectForKey:@"message"];
        }else
        {
            errorMessage = error.localizedDescription;
        }
        if (fail) {
            fail( errorMessage , error);
        }
    }];
    return operation;
}

- (void)postImageWithImage:(UIImage *)image andType:(NSInteger)type andSuccess:(SuccessBlock)success andFail:(FailBlock)fail{
    
    [self POST_Field_Url:@"api/Common/UploadFile" Params:@{@"File":[TGTools base64WithImage:image],@"Type":@(type)} successBlock:^(id returnValue) {
        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            success([returnValue objectForKey:@"Data"]);
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            fail(nil,nil);
        }
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        fail(nil,nil);
    }];
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (AFHTTPSessionManager *)httpManager{
#warning ----新增
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manage.responseSerializer=response;
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    if (coor.latitude!=0) {
        if (coor.latitude>0) {
            [serializer setValue:[NSString stringWithFormat:@"%f",coor.latitude] forHTTPHeaderField:@"m-lat"];
            [serializer setValue:[NSString stringWithFormat:@"%f",coor.longitude] forHTTPHeaderField:@"m-lng"];
        
        }else{
            [self.locationManager startUpdatingLocation];
            [serializer setValue:@"" forHTTPHeaderField:@"m-lat"];
            [serializer setValue:@"" forHTTPHeaderField:@"m-lng"];
        }
    }
    [serializer setValue:@"1" forHTTPHeaderField:@"m-lt"];
    [serializer setValue:[self internetStatus] forHTTPHeaderField:@"m-nw"];
    [serializer setValue:@"1.0" forHTTPHeaderField:@"m-iv"];
    [serializer setValue:VERSION forHTTPHeaderField:@"m-cv"];
    [serializer setValue:@"ios" forHTTPHeaderField:@"m-ct"];
    
    [serializer setValue:[NSString stringWithFormat:@"%f",SCREEN_WIDTH] forHTTPHeaderField:@"m-cw"];
    [serializer setValue:[NSString stringWithFormat:@"%f",SCREEN_HEIGHT] forHTTPHeaderField:@"m-ch"];
//    ///官网下载
    [serializer setValue:@"2" forHTTPHeaderField:@"m-sr"];
    ///AppStore下载
//    [serializer setValue:@"10" forHTTPHeaderField:@"m-sr"];
    
    
    NSString *uuid = [WMKeyChain load:KeyChain_UUID];
    if (!uuid) {
        [WMKeyChain save:KeyChain_UUID
                    data:[UIDevice currentDevice].identifierForVendor.UUIDString];
    }
    uuid = [WMKeyChain load:KeyChain_UUID];
    [serializer setValue:uuid forHTTPHeaderField:@"m-ii"];
    manage.requestSerializer = serializer;
    return manage;
}

#pragma mark - 取消网络请求
- (void)cancelRequest
{
    if ([self httpManager].tasks.count > 0) {
        NSLog(@"返回时取消网络请求");
        [[self httpManager].tasks makeObjectsPerformSelector:@selector(cancel)];
        //NSLog(@"tasks = %@",manager.tasks);
    }
}
- (CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager=[[CLLocationManager alloc]init];
        _locationManager.delegate=self;
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_locationManager startUpdatingLocation];
    }
    return _locationManager;
}

-(NSString *)internetStatus {
    AFNetworkReachabilityManager *reachability   = [AFNetworkReachabilityManager sharedManager];
    AFNetworkReachabilityStatus internetStatus = [reachability networkReachabilityStatus];
    NSString *net = @"wifi";
    switch (internetStatus) {
        case AFNetworkReachabilityStatusReachableViaWiFi:
            net = @"wifi";
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            net = @"4g";
            break;
        case AFNetworkReachabilityStatusNotReachable:
            net = @"当前无网路连接";
            break;
        default:
            break;
    }
    return net;
}

#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    coor.latitude=-1.0;
    if (self.locationBlock) {
        self.locationBlock();
    }
}

#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    coor=currentLocation.coordinate;
    if (self.locationBlock) {
        self.locationBlock();
    }

    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:manager.location completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
            if (place.locality) {
                self.city=place.locality;
                break;
            }
        }
        
    }];
    
}


- (void)login{
    [UserModel clean];
    UIViewController *vc=[BaseVM manage].viewCtrl;
    if ([vc isMemberOfClass:[LoginVC class]]) {
        return;
    }
    if ([NSThread isMainThread]) {
        LoginVC *vc=[[UIStoryboard storyboardWithName:@"CLogin" bundle:nil]instantiateViewControllerWithIdentifier:@"LoginVC"];
        [[BaseVM manage].viewCtrl.navigationController pushViewController:vc animated:YES];
        [BaseVM manage].viewCtrl=vc;
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            LoginVC *vc=[[UIStoryboard storyboardWithName:@"CLogin" bundle:nil]instantiateViewControllerWithIdentifier:@"LoginVC"];
            
            [[BaseVM manage].viewCtrl.navigationController pushViewController:vc animated:YES];
            [BaseVM manage].viewCtrl=vc;
        });
    }
    
}

static BaseVM *n_manager=nil;
+(BaseVM *)manage
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        n_manager=[[BaseVM alloc]init];
        [n_manager.locationManager startUpdatingLocation];
    });
    return n_manager;
}

- (NSMutableArray *)lotteryArr{
    if (!_lotteryArr) {
        
        _lotteryArr=[[NSMutableArray alloc]init];
    }
    return _lotteryArr;
}

- (LotteryNumType)getType:(NSInteger)lType{
    LotteryNumType lotteryType;
    if (lType==1) {
        lotteryType=LotteryNumTypeLottery3D;
    }else if (lType==2){
        lotteryType=LotteryNumTypeChromosphere;
    }else if (lType==3){
        lotteryType=LotteryNumTypeSevenStars;
    }else if (lType==4){
        lotteryType=LotteryNumTypeBrings;
    }else if (lType==5){
        lotteryType=LotteryNumTypeLottery;
    }else if (lType==6){
        lotteryType=LotteryNumTypeArrangement3;
    }else if (lType==7){
        lotteryType=LotteryNumTypeArrangement5;
    }else if (lType==8){
        lotteryType=LotteryNumTypeSevenLecai;
    }else if (lType<15){
        lotteryType=LotteryNumTypeAllTime;
    }else if (lType<38){
        lotteryType=LotteryNumType11Select5;
    }else if (lType<51){
        lotteryType=LotteryNumTypeNearlyThree;
    }else if (lType<60){
        lotteryType=LotteryNumTypeHappy10;
    }else if (lType<63){
        lotteryType=LotteryNumTypeHappy12;
    }else if (lType==64){
        lotteryType=LotteryNumTypeLuckyAirship;
    }else if (lType<65){
        lotteryType=LotteryNumTypeCarPK10;
    }else{
        lotteryType=LotteryNumTypeNearlyThree;
    }
    return lotteryType;
}

- (NSString *)getTitle:(LotteryNumType)lType{
    if (lType==LotteryNumTypeLottery3D) {
        return @"福彩3D";
    }else if (lType==LotteryNumTypeChromosphere){
        return @"双色球";
    }else if (lType==LotteryNumTypeSevenStars){
        return @"七星彩";
    }else if (lType==LotteryNumTypeBrings){
        return @"大乐透";
    }else if (lType==LotteryNumTypeLottery){
        return @"六合彩";
    }else if (lType==LotteryNumTypeArrangement3){
        return @"排列三";
    }else if (lType==LotteryNumTypeArrangement5){
        return @"排列五";
    }else if (lType==LotteryNumTypeSevenLecai){
        return @"七乐彩";
    }else if (lType==LotteryNumTypeAllTime){
        return @"时时彩";
    }else if (lType==LotteryNumType11Select5){
        return @"11选5";
    }else if (lType==LotteryNumTypeNearlyThree){
        return @"排列三";
    }else if (lType==LotteryNumTypeHappy10){
        return @"快乐十分";
    }else if (lType==LotteryNumTypeHappy12){
        return @"快乐十二";
    }else if (lType==LotteryNumTypeCarPK10){
        return @"北京赛车";
    }else if (lType==LotteryNumTypeLuckyAirship){
        return @"幸运飞艇";
    }else{
        return @"快三";
    }
    return nil;
}

- (NSString *)city{
    if (!_city) {
        return @"";
    }
    return _city;
}

@end

